import 'package:flutter/material.dart';

class Home extends StatelessWidget {
  const Home({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: MyState(),
      appBar: AppBar(
        title: Text("跨组件 数据传递 inheritedWidget"),
      ),
    );
  }
}

// inheritedWidget  跨组件数据传递
class MyState extends StatefulWidget {
  const MyState({Key? key}) : super(key: key);
  @override
  State<MyState> createState() => _MyStateState();
}

class _MyStateState extends State<MyState> {
  int num = 0;

  void _increment() {
    setState(() {
      num++;
    });
  }

  void _decrement() {
    setState(() {
      num--;
    });
  }

  @override
  Widget build(BuildContext context) {

    //3. 用InheritedWidget组件 作为父组件
    return ShareDataWidget(
      num: num,
      child: Center(
        child: Column(
          children: [
            ElevatedButton(onPressed: _decrement, child: Text("递减")),
            Padding(
              padding: EdgeInsets.all(10),
              //4.跨组件数据传递
              child: MyCounter(),
            ),
            ElevatedButton(onPressed: _increment, child: Text("递增"))
          ],
        ),
      ),
    );
  }
}

class MyCounter extends StatelessWidget {
  const MyCounter({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text(ShareDataWidget.of(context)!.num.toString()),
    );
  }
}


//跨组件数据传递
class ShareDataWidget extends InheritedWidget {
  final Widget child;

  //1.定义属性
  final int num;

  //2.修改构造方法
  ShareDataWidget({Key? key, required this.child, required this.num})
      : super(key: key, child: child);
  static ShareDataWidget? of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<ShareDataWidget>();
  }

  @override
  bool updateShouldNotify(ShareDataWidget oldWidget) {
    return true;
  }
}
